const db = wx.cloud.database()
Page({
  data: {
    index: 0,
    picker: ['男', '女'],
    personInfo: { name: '', mobile:'',sex:'男'}
  },
  PickerChange(e) {
    let index=e.detail.value
    let personInfo = this.data.personInfo
    personInfo.sex = index==1 ? '女' : '男'
    this.setData({
      index: index, personInfo: personInfo
    })
  },
  updateValue: function (event) {
    let name = event.currentTarget.dataset.name;
    let personInfo = this.data.personInfo
    personInfo[name] = event.detail.value
    this.setData({
      personInfo: personInfo
    })
  },

  submitform: function (event) {
    var mobile = this.data.personInfo.mobile;
    var name = this.data.personInfo.name;
    var sex = this.data.personInfo.sex;
    var mobilevalid = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (name == '') {
      wx.showToast({
        title: '请输入用户名',
        icon: 'succes',
        duration: 1000,
        mask: true
      })
      return false
    } else if (mobile == '') {
      wx.showToast({
        title: '手机号不能为空',
      })
      return false
    }
    else if (mobile.length != 11) {
      wx.showToast({
        title: '手机号长度有误！',
        icon: 'success',
        duration: 1500
      })
      return false;
    }
    if (!mobilevalid.test(mobile)) {
      wx.showToast({
        title: '手机号有误！',
        icon: 'success',
        duration: 1500
      })
      return false;
    }
    wx.cloud.callFunction({
      name: 'translate',
      data: {
        text: name
      },
      success: function (res) {
        console.log(res.result.searchfeild)
        db.collection('contact').add({
          // data 字段表示需新增的 JSON 数据
          data: {
            name: name,
            mobile:mobile,
            sex: sex,
            searchfeild: res.result.searchfeild
          }
        })
          .then(res => {
            wx.showToast({
              title: '添加成功...',
              icon: 'none',
              duration: 1500
            })
            
          })

      }
    })
  }
})